/**
 * 模拟实时消息数据生成器
 * 当外部API不可用时提供模拟数据
 */

import type { MessageItem } from '../types'

export interface MockIoTMessage {
  id: string;
  type: 'info' | 'warning' | 'success' | 'error';
  content: string;
  time: string;
  deviceId?: string;
  deviceName?: string;
  source: 'device' | 'system';
}

export class MockDataService {
  private static messageCounter = 0;
  private static deviceStates: Record<string, any> = {
    fan_flag: false,
    airconditioner_flag: false,
    heating_flag: false,
    lamplight_flag: false,
    mode_flag: 'Auto',
    alarm: false
  };
  
  /**
   * 生成模拟IoT设备消息
   */
  static generateMockIoTMessages(): MockIoTMessage[] {
    const messages: MockIoTMessage[] = [];
    
    // 随机生成设备状态变化 (20% 概率)
    if (Math.random() < 0.2) {
      const deviceChange = this.generateDeviceStateChange();
      if (deviceChange) {
        messages.push(deviceChange);
      }
    }
    
    // 如果没有设备变化或需要第二条消息，生成系统状态消息
    if (messages.length === 0 || Math.random() < 0.5) {
      const systemMessage = this.generateSystemMessage();
      messages.push(systemMessage);
    }
    
    // 确保最多返回2条消息
    return messages.slice(0, 2);
  }
  
  /**
   * 生成设备状态变化消息
   */
  private static generateDeviceStateChange(): MockIoTMessage | null {
    const devices = Object.keys(this.deviceStates);
    const randomDevice = devices[Math.floor(Math.random() * devices.length)];
    
    let newState: any;
    if (randomDevice === 'mode_flag') {
      newState = this.deviceStates[randomDevice] === 'Auto' ? 'Manual' : 'Auto';
    } else {
      newState = !this.deviceStates[randomDevice];
    }
    
    // 更新状态
    this.deviceStates[randomDevice] = newState;
    
    const deviceNames: Record<string, string> = {
      fan_flag: '风扇设备',
      airconditioner_flag: '空调设备',
      heating_flag: '暖气设备',
      lamplight_flag: '灯光设备',
      mode_flag: '设备模式',
      alarm: '报警状态'
    };
    
    const deviceName = deviceNames[randomDevice];
    let messageType: MockIoTMessage['type'] = 'info';
    let content = '';
    
    if (randomDevice === 'alarm') {
      messageType = newState ? 'error' : 'success';
      content = newState ? `⚠️ ${deviceName} 触发报警！` : `✅ ${deviceName} 报警解除`;
    } else if (randomDevice === 'mode_flag') {
      messageType = 'info';
      content = `🔄 用户切换${deviceName}为${newState}模式`;
    } else {
      messageType = newState ? 'success' : 'info';
      content = newState ? `✨ 用户开启了${deviceName}` : `🔌 用户关闭了${deviceName}`;
    }
    
    this.messageCounter++;
    
    return {
      id: `mock_device_${Date.now()}_${this.messageCounter}`,
      type: messageType,
      content,
      time: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }),
      deviceId: `mock_device_${randomDevice}`,
      deviceName,
      source: 'device'
    };
  }
  
  /**
   * 生成系统状态消息
   */
  private static generateSystemMessage(): MockIoTMessage {
    const systemMessages = [
      { content: '🏫 智慧校园系统运行正常', type: 'success' as const },
      { content: '📊 环境数据更新完成', type: 'info' as const },
      { content: '🔍 设备监控系统运行中', type: 'success' as const },
      { content: '📡 网络连接状态良好', type: 'info' as const },
      { content: '🌡️ 温湿度监测正常', type: 'success' as const },
      { content: '🔋 设备电量状态良好', type: 'info' as const },
      { content: '💻 系统自检完成', type: 'success' as const },
      { content: '📱 设备通信正常', type: 'info' as const },
      { content: '🔐 安全监控运行中', type: 'success' as const },
      { content: '⚡ 能耗监测更新', type: 'info' as const }
    ];
    
    const randomMessage = systemMessages[Math.floor(Math.random() * systemMessages.length)];
    this.messageCounter++;
    
    return {
      id: `mock_system_${Date.now()}_${this.messageCounter}`,
      type: randomMessage.type,
      content: randomMessage.content,
      time: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }),
      source: 'system'
    };
  }
  
  /**
   * 转换为MessageItem格式
   */
  static convertToMessageItems(mockMessages: MockIoTMessage[]): MessageItem[] {
    return mockMessages.map(msg => ({
      id: msg.id,
      type: msg.type,
      content: msg.content,
      time: msg.time,
      priority: msg.type === 'error' ? 'high' : msg.type === 'warning' ? 'medium' : 'low'
    }));
  }
  
  /**
   * 获取当前设备状态（用于调试）
   */
  static getCurrentDeviceStates() {
    return { ...this.deviceStates };
  }
  
  /**
   * 重置设备状态
   */
  static resetDeviceStates() {
    this.deviceStates = {
      fan_flag: false,
      airconditioner_flag: false,
      heating_flag: false,
      lamplight_flag: false,
      mode_flag: 'Auto',
      alarm: false
    };
    this.messageCounter = 0;
  }
}
